from .models import Vocation
from .serializers import VocationSerializer
from rest_framework.response import Response
from rest_framework import viewsets

class vocationSet(viewsets.GenericViewSet):
    queryset = Vocation.objects.all().order_by('id')
    serializer_class = VocationSerializer

    def get_all_data(self, request):
        '''
        获取所有数据
        '''
        res = {'state': 'success', 'msg': '获取成功', 'data': []}
        data = self.get_queryset()
        # 数据分页处理
        data = self.paginate_queryset(data)
        serializer = self.get_serializer(data, many=True)
        # 返回分页的前一页、后一页和总数据量
        r = self.get_paginated_response(serializer.data)
        res['data'] = r.data
        return Response(res)

    def get_one_data(self, request):
        '''
        获取单行数据
        '''
        res = {'state': 'success', 'msg': '获取成功', 'data': {}}
        id = request.GET.get('id', '')
        if id:
            data = self.get_queryset().filter(id=id).first()
            if data:
                serializer = self.get_serializer(data)
                res['data'] = serializer.data
        return Response(res)

    def create_data(self, request):
        '''
        新增数据
        '''
        res = {'state': 'fail', 'msg': '新增失败'}
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            res = {'state': 'success', 'msg': '新增成功'}
        return Response(res)


    def update_data(self, request):
        '''
        修改数据
        '''
        res = {'state': 'fail', 'msg': '修改失败'}
        id = request.data.get('id', 0)
        operation = self.get_queryset().filter(id=id).first()
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if operation:
            # 修改数据
            serializer.update(operation, request.data)
            res = {'state': 'success', 'msg': '修改成功'}
        return Response(res)
